package registerFunction;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import encryption.DigestUtil;
import theBeans.student;
import theDaoFactory.DaoFactory;
import theDaos.IStudentDao;

/**
* 
* 功能：发送邮箱功能处理
* @author itshenjin
* @author 2018年12月11日
*
*/
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String sessionCode = (String) req.getSession().getAttribute("code");
		System.out.println(sessionCode);
		//  获取session中的验证码
		if(sessionCode != null) 
		{
			//  获取页面提交的验证码
			String inputCode = req.getParameter("code");
			System.out.println("页面提交的验证码:" + inputCode);
			if (sessionCode.toLowerCase().equals(inputCode.toLowerCase())) 
			{
				String sid=req.getParameter("sid");
				//数据库查表，若有对应ID则绑定，否则跳转到错误页
				IStudentDao studentDaoInstance=DaoFactory.getStudentDaoInstance();
				student studentOption=new student();
				studentOption=studentDaoInstance.findBySid(sid);
				if(studentOption!=null)
				{
					// 把用户名和密码等一系列信息插入到数据库中
					String username = req.getParameter("username");
					String password = req.getParameter("password");
					String passwordEncrypted=DigestUtil.sha1(password);
					String emailAddress=req.getParameter("email");
					int result=0;
					result=studentDaoInstance.update(sid, username, passwordEncrypted, emailAddress);
				
					if(result==1)
					{
						//  验证成功，跳转成功页面
						req.getSession().setAttribute("ifLogin", 1);
						resp.sendRedirect("login.jsp");
					}
					else
					{
						req.setAttribute("errorInfo", "");
						req.setAttribute("toURL", "");
						req.getRequestDispatcher("errorPage.jsp").forward(req, resp);
					}
					
				}
				else
				{
					req.setAttribute("errorInfo", "");
					req.setAttribute("toURL", "");
					req.getRequestDispatcher("errorPage.jsp").forward(req, resp);
				}
			}
			else 
			{
				//  验证失败
				req.setAttribute("errorInfo", "");
				req.setAttribute("toURL", "");
				req.getRequestDispatcher("errorPage.jsp").forward(req, resp);
			}
		}
		else 
		{
			//  验证失败
			req.setAttribute("errorInfo", "");
			req.setAttribute("toURL", "");
			req.getRequestDispatcher("errorPage.jsp").forward(req, resp);
		}
		//  移除session中的验证码
		req.removeAttribute("code");
	}
}